package com.neulogistics.contrib.procuredcenter.api.application.query;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neulogistics.contrib.procuredcenter.api.application.converter.TreeConverter;
import com.neulogistics.contrib.procuredcenter.api.application.viewmodel.TreeNodeViewModel;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.po.GoodsListPO;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.po.GoodsSetPO;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.service.IGoodsListPOService;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.service.IGoodsSetPOService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TreeQueryService implements ITreeQueryService {
    @Resource
    IGoodsListPOService goodsListPOService;

    @Resource
    IGoodsSetPOService goodsSetPOService;

    @Override
    public List<TreeNodeViewModel> getTree() {
        List<GoodsListPO> goodsListPOS = goodsListPOService.list();

        List<TreeNodeViewModel> result = goodsListPOS
                .parallelStream()
                .map(TreeConverter::ListPOToVM)
                .sorted(Comparator.comparing(TreeNodeViewModel::getName))
                .collect(Collectors.toList());

        result.forEach( list ->{
            LambdaQueryWrapper<GoodsSetPO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(GoodsSetPO::getListId, list.id);
            List<GoodsSetPO> goodsSetPOS = goodsSetPOService.list(queryWrapper);
            List<TreeNodeViewModel> children = goodsSetPOS
                    .parallelStream()
                    .map(TreeConverter::SetPOToVM)
                    .sorted(Comparator.comparing(TreeNodeViewModel::getName))
                    .collect(Collectors.toList());
            list.setChildren(children);
        });

        return result;
    }
}
